define(['app', 'pagination', 'datetime', 'autocomplete', 'editor', 'filesaver', 'fileupload','floatlayer'], function(appCRM) {
    'use strict';

    /*发票记录控制器*/
    appCRM.controller('Invoice', function($scope, dataFactoryCRM, $q, Upload, $http) {
        $scope.invoice_list;
        $scope.CustomerInf;
        $scope.imgAdd = new Array();
        $scope.editPic = new Array();
        $scope.invoicepage = { pageAll: 1, pageNow: 1, pageSize: 20, k: 3 };
        $scope.payeetypes = [{ k: '1', v: '北京和众汇富咨询有限公司北京分公司' }, { k: '2', v: '北京和众汇富咨询有限公司山东分公司' },
            { k: '3', v: '北京和众汇富咨询有限公司天津分公司' }
        ];
        $scope.customer_name = "";
        $scope.create_time = "";
        $scope.pay_name = "";
        $scope.end_time = "";
        $scope.key;
        $scope.CustomerInf = [{}];

        /*双弹窗*/
        $scope.msgAttention = function() {
            $('.ui.second').modal({
                allowMultiple: true,
                closable: false,
                onDeny: function() {
                    window.alert('Wait not yet!');
                    return false;
                },
            }).modal('show');
        };

        /*
         *按照搜索条件显示发票列表
         */
        $scope.invoiceDataList = function(key) {
            $scope.key = key;
            var indexUrl = 'invoice/index?p=' + $scope.invoicepage.pageNow + '&psize=' + $scope.invoicepage.pageSize + '&status=' + $scope.key;
            indexUrl = indexUrl + '&customer_name=' + $scope.customer_name + '&create_time=' + $scope.create_time + '&end_time=' + $scope.end_time + '&pay_name=' + $scope.pay_name;
            $scope.$emit("BUSY");
            dataFactoryCRM.getDataByAPI(indexUrl).then(function(returnData) {
                $scope.rcode = returnData.rcode;
                $scope.invoicepage.pageSize = returnData.psize;
                $scope.invoicepage.pageAll = returnData.pall;
                $scope.invoicepage.pageNow = returnData.p;
                $scope.invoice_list = returnData.data;
            });
            $scope.$emit("NOTBUSY");
        }
        $scope.getInvoiceList = function(key) {
                if (key) $scope.key = key;
                $scope.invoiceDataList($scope.key);
            }

        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function(){
           $scope.invoiceDataList($scope.key);
        });
            /*
             *发票管理搜索
             */
        $scope.search = function() {
            $scope.getInvoiceList();
        }

        /*获取客户付款、发票信息*/
        $scope.getCusInfo = function(search_neirong,customerid,pay_name,invoice_id) {
            var par = 'search_neirong=' + search_neirong+'&customerid='+customerid+'&pay_name='+pay_name + '&invoice_id=' + invoice_id;
            dataFactoryCRM.postDataByAPI('invoice/getCustomerInfo', par)
                .then(function(d) {
                    $scope.customerVerify = d.customerVerify; //付款或发票信息是否存在
                    if (d.rcode) {
                        $scope.invpay_name = d.invpay_name;
                        $scope.payrecord_rcode = d.payrecord_rcode;
                        $scope.invoice_rcode = d.invoice_rcode;
                        $scope.payrecordInfo = d.payrecordInfo; //付款信息
                        $scope.total_paymount = d.total_paymount; //总付款金额
                        $scope.invoiceInfo = d.invoiceInfo; //发票信息
                        $scope.total_money = d.total_money; //发票总金额
                    } else {
                        $scope.customerid = '';
                    }
                });
        }
        $scope.registerHiddenBlur = function(hiddenID, visibleID) {
                $('#' + visibleID).blur(function() {
                    //延时触发blur，目的是让hidden input先于blur被赋值
                    setTimeout(function() {
                        $('#' + hiddenID).trigger('blur');
                    }, 100);
                });
            }
            /*自动补全触发事件*/
        $scope.selectCustomers = function(selected) {
            if (selected) {
                $scope.selecteds = selected;
                var cid = selected.originalObject.customer_id;
                if (selected.originalObject.customer_id) {
                    $scope.customerbackup = selected.originalObject.customer_id;
                };
                $scope.customerid = cid; //添加客户id
                $("#customerid").val(cid);
                if("payname" == selected.originalObject['search_neirong']){ //按照付款人信息查找付款信息
                    var search = selected.originalObject['pay_name'];
                    $scope.getCusInfo("payname",'',search, '');
                }else if("phone" == selected.originalObject['search_neirong']){//按照电话号码查找付款信息
                    $scope.getCusInfo("phone",cid,'', '');
                }
            } else {
                $scope.customerVerify = 0;
                $scope.delivetype = 0;
                $scope.invoicetype = 0;
                $('#frm-add input').val('');
                $('#frm-imgPost input').val('');
                $('#delivery-add input').val('');
                //去掉发票默认选择
                $("input:radio[name='frequency1']").attr("checked", false);
                $("input:radio[name='frequency1']").removeAttr('checked');
                $("input:radio[name='frequency2']").attr("checked", false);
                $("input:radio[name='frequency2']").removeAttr('checked');
                $scope.tax = '';
                $scope.imgPost_taxs = '';
                $scope.add_money = "";
                $scope.add_title = "";
                $scope.imgPost_title = "";
                $scope.imgPost_money = "";
                $scope.customer_nickname = "";
                $scope.customer_phone = "";
                $scope.customer_address = "";
            }
        }

        //自动补全体验度
        $scope.CustomerChanged = function($item) {
            $scope.detectUser = $item;
        }
        //添加-监听输入付款人信息
        $scope.$watch('detectUser', function(newvalue, oldvalue) {
            if (newvalue != oldvalue) {
                dataFactoryCRM.postDataByAPI('invoice/getCustomerId', 'pay_name=' + $scope.detectUser)
                    .then(function(d) {
                        if (d.rcode) {
                            $scope.CustomerInf = d.data;
                        } else {
                            $scope.CustomerInf = [{}];
                            $scope.customeridrecord = 'false';
                        }
                    });
            }
            if ($scope.detectUser || $scope.customeridrecord == 'false') {
                $('#customerid').val('false');
            }else if (!$scope.detectUser) {
                $('#customerid').val('');
            }
        });


            /*计算税额*/
        $scope.getTaxs = function(money) {
                var money = parseFloat(money);
                var tax = Math.round(parseFloat((money - money / 1.06)));
                return tax;
            }
            /*添加发票金额，获取税额*/
        $scope.setTax = function() {
                $scope.tax = $scope.getTaxs($scope.add_money);
            }
            /*编辑发票金额，获取税额*/
        $scope.setEdit_tax = function() {
                $scope.edit_data.tax = $scope.getTaxs($scope.edit_money);
            }
            /*添加专票发票金额，获取税额*/
        $scope.imgPost_tax = function() {
                $scope.imgPost_taxs = $scope.getTaxs($scope.imgPost_money);
            }
            /*编辑专票发票金额，获取税额*/
        $scope.imgPostEdit_tax = function() {
                $scope.imgPostEdit_taxs = $scope.getTaxs($scope.imgPostEdit_money);
            }
            /*选择发票类型*/
        $scope.switchType = function(key) {
            $scope.invoicetype = key;
            $scope.getPayInfo();
            $('#selectType').removeClass('ui basic red pointing prompt label transition visible');
            document.getElementById("selectType").innerHTML = '';
            setTimeout(function() {
                $('.modal.add').modal('refresh');
            }, 100);
        };

        /*选择邮寄情况：邮寄信息赋默认值*/
        $scope.deliveType = function(key) {
            $scope.delivetype = key;
            var pay_id = $("input:checkbox[name='chbidsAdd']:checked").map(function(index, elem) {
                return $(elem).val();
            }).get().join(',');
            $("#delivery-add").form('reset');
            dataFactoryCRM.getDataByAPI('invoice/getPayInfos?pay_id=' + pay_id).then(function(d) {
                if (d.rcode) {
                    if (d.deliveInfo.length > 0 && d.customerInfo) {
                        $('#delivery-add input[name="recipients"]').val(d.deliveInfo[0]['nickname']);
                        $('#delivery-add input[name="phone"]').val(d.deliveInfo[0]['phone']);
                        $('#delivery-add input[name="address"]').val(d.deliveInfo[0]['address']);
                    } else if (d.deliveInfo.length == 0 && d.customerInfo) {
                        $('#delivery-add input[name="recipients"]').val(d.customerInfo['nickname']);
                        $('#delivery-add input[name="phone"]').val(d.customerInfo['phone']);
                        $('#delivery-add input[name="address"]').val(d.customerInfo['address']);
                    }
                }
            });
            $('#add_sty').removeClass('ui basic red pointing prompt label transition visible');
            document.getElementById("add_sty").innerHTML = '';
            setTimeout(function() {
                $('.modal.add').modal('refresh');
            }, 100);
            $('#delivery-add input[name="send_time"]').val($scope.getToday());
        }

        /*添加-根据pay_id获取付款信息、发票信息和邮寄信息*/
        $scope.getCustomerInfo = function(pay_id) {
            dataFactoryCRM.getDataByAPI('invoice/getPayInfos?pay_id=' + pay_id).then(function(d) {
                if (d.rcode) {
                    if ($scope.invoicetype == 1) { //普通发票
                        $scope.add_title = d.customerInfo['pay_name'];
                        $scope.add_money = d.payMountSum['paymount'];
                        $scope.tax = $scope.getTaxs($scope.add_money);
                    } else if ($scope.invoicetype == 2) { //专票
                        $scope.imgPost_title = d.customerInfo['pay_name'];
                        $scope.imgPost_money = d.payMountSum['paymount'];
                        $scope.imgPost_taxs = $scope.getTaxs($scope.imgPost_money);
                    }
                    if (d.deliveInfo.length) {
                        $('#delivery-add input[name="recipients"]').val(d.deliveInfo[0]['nickname']);
                        $('#delivery-add input[name="phone"]').val(d.deliveInfo[0]['phone']);
                        $('#delivery-add input[name="address"]').val(d.deliveInfo[0]['address']);
                    } else {
                        $('#delivery-add input[name="recipients"]').val(d.customerInfo['nickname']);
                        $('#delivery-add input[name="phone"]').val(d.customerInfo['phone']);
                        $('#delivery-add input[name="address"]').val(d.customerInfo['address']);
                    }
                }
            });
        }

        /*编辑-根据pay_id获取付款信息*/
        $scope.getCustomerInfoEdit = function(pay_id) {
            dataFactoryCRM.getDataByAPI('invoice/getPayInfos?pay_id=' + pay_id).then(function(d) {
                if (d.rcode) {
                    if ($scope.edit_data_invoicetype == 1) { //普通发票
                        $scope.edit_title = d.customerInfo['pay_name'];
                        $scope.edit_money = d.payMountSum['paymount'];
                        $scope.edit_data.tax = $scope.getTaxs($scope.edit_money);
                    } else if ($scope.edit_data_invoicetype == 2) { //专票
                        $scope.imgPostEdit_title = d.customerInfo['pay_name'];
                        $scope.imgPostEdit_money = d.payMountSum['paymount'];
                        $scope.imgPostEdit_taxs = $scope.getTaxs($scope.imgPostEdit_money);
                    }
                }
            });
        }

        /*添加-根据pay_id获取付款信息*/
        $scope.getPayInfo = function() {
            var pay_id = $("input:checkbox[name='chbidsAdd']:checked").map(function(index, elem) {
                return $(elem).val();
            }).get().join(',');
            if (pay_id.length > 1) {
                $('#selectPaysAdd').removeClass('ui basic red pointing prompt label transition visible');
                document.getElementById("selectPaysAdd").innerHTML = '';
            }
            if (pay_id.length < 1) { //没有选择删除项
                return;
            }
            $scope.getCustomerInfo(pay_id);
        }

        /*编辑-根据pay_id获取付款信息*/
        $scope.getPayInfoEdit = function() {
                $scope.pay_idEdit = $("input:checkbox[name='chbidsEdit']:checked").map(function(index, elem) {
                    return $(elem).val();
                }).get().join(',');
                if ($scope.pay_idEdit.length > 1) { //选择流水后错误提示隐藏
                    $('#selectPaysEdit').removeClass('ui basic red pointing prompt label transition visible');
                    document.getElementById("selectPaysEdit").innerHTML = '';
                }
                $scope.getCustomerInfoEdit($scope.pay_idEdit);
            }
            /*获取当前日期*/
        $scope.getToday = function() {
            var date = new Date();
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            if (month < 9) {
                month = '0' + month;
            }
            var today = year + '-' + month + '-' + day;
            return today;
        }
        $scope.pic_alt = "";
        /*添加发票页面*/
        $scope.showAdd = function() {
                $("#name-check").form('reset');
                $("#frm-add").form('reset');
                $('#frm-imgPost input').val('');
                $('#delivery-add input').val('');
                $scope.imgAdd = new Array();
                $('#add_sty').removeClass('ui basic red pointing prompt label transition visible');
                document.getElementById("add_sty").innerHTML = '';
                $('#selectType').removeClass('ui basic red pointing prompt label transition visible');
                document.getElementById("selectType").innerHTML = '';
                $scope.$broadcast('angucomplete-alt:clearInput');
                $scope.tax = "";
                $scope.imgPost_taxs = "";
                $scope.invoicetype = 0;
                $scope.customerVerify = 0;
                $scope.delivetype = 0; //默认付款、发票信息、邮寄信息不显示
                $('#payeeID>.ui.dropdown>.text').text('请选择收款单位');
                //去掉发票默认选择
                $("input:radio[name='frequency1']").attr("checked", false);
                $("input:radio[name='frequency1']").removeAttr('checked');
                $("input:radio[name='frequency2']").attr("checked", false);
                $("input:radio[name='frequency2']").removeAttr('checked');
                $('.modal.add').modal({
                    allowMultiple: true,
                    observeChanges: true,
                    onApprove: function() {
                        var pay_id = $("input:checkbox[name='chbidsAdd']:checked").map(function(index, elem) {
                            return $(elem).val();
                        }).get().join(',');
                        if ($('#name-check').form('is valid')) {
                            if (pay_id) { //选择发票流水
                                if ($scope.invoicetype == 1) { //普通发票
                                    if ($scope.delivetype == 1) { //发票邮寄
                                        if ($('#frm-add').form('is valid') && $('#delivery-add').form('is valid')) {
                                            $scope.addInvoice($('#frm-add').serialize() + '&delivetype=' + $scope.delivetype + '&pay_id=' + pay_id + '&' + $('#delivery-add').serialize() + '&status=0' + '&customer_id=' + $scope.customerid + '&tax=' + $scope.tax);
                                        } else return false;
                                    } else if ($scope.delivetype == 2) { //发票自取
                                        if ($('#frm-add').form('is valid')) {
                                            $scope.addInvoice($('#frm-add').serialize() + '&delivetype=' + $scope.delivetype + '&pay_id=' + pay_id + '&status=2' + '&customer_id=' + $scope.customerid + '&tax=' + $scope.tax);
                                        } else return false;
                                    } else { //未选择邮寄方式，错误提示
                                        $('#add_sty').addClass('ui basic red pointing prompt label transition visible');
                                        document.getElementById("add_sty").innerHTML = '请选择邮寄情况！';
                                        return false;
                                    }
                                } else if ($scope.invoicetype == 2) { //专票
                                    if ($scope.delivetype == 1) { //发票邮寄
                                        if ($('#frm-imgPost').form('is valid') && $('#delivery-add').form('is valid')) {
                                            $scope.imagesPost($('#frm-imgPost').serialize() + '&delivetype=' + $scope.delivetype + '&pay_id=' + pay_id + '&' + $('#delivery-add').serialize() + '&status=0' + '&customer_id=' + $scope.customerid);
                                        } else return false;
                                    } else if ($scope.delivetype == 2) {
                                        if ($('#frm-imgPost').form('is valid')) { //发票自取
                                            $scope.imagesPost($('#frm-imgPost').serialize() + '&delivetype=' + $scope.delivetype + '&pay_id=' + pay_id + '&status=2' + '&customer_id=' + $scope.customerid);
                                        } else return false;
                                    } else { //未选择邮寄方式，错误提示
                                        $('#add_sty').addClass('ui basic red pointing prompt label transition visible');
                                        document.getElementById("add_sty").innerHTML = '请选择邮寄情况！';
                                        return false;
                                    }
                                } else { //未选择发票类型，错误提示
                                    $('#selectType').addClass('ui basic red pointing prompt label transition visible');
                                    document.getElementById("selectType").innerHTML = '请选择发票类型！';
                                    return false;
                                }
                            } else { //未选择发票对应流水，错误提示
                                $('#selectPaysAdd').addClass('ui basic red pointing prompt label transition visible');
                                document.getElementById("selectPaysAdd").innerHTML = '请选择付款流水！';
                                return false;
                            }
                        } else return false;
                    }
                }).modal('show');
            }
            /*添加普通发票功能*/
        $scope.addInvoice = function(_url) {
            $scope.$emit("BUSY");
            $scope.busy = dataFactoryCRM.postDataByAPI('invoice/add', _url).then(function(d) {
                if (d.rcode) {
                    $(".ui.small.modal.addOk").modal('show');
                    setTimeout(function() {
                        $('.ui.small.modal.addOk').modal('hide')
                    }, 3000);
                    $scope.invoicetype = 0;
                    $scope.customerVerify = 0;
                    $scope.delivetype = 0; //默认付款、发票信息、邮寄信息不显示
                    $scope.getInvoiceList(); //添加新发票后，按照搜索条件刷新
                } else {
                    $(".ui.modal.addFail").modal('show');
                    setTimeout(function() {
                        $('.ui.modal.addFail').modal('hide')
                    }, 3000);
                    $scope.invoicetype = 0;
                    $scope.customerVerify = 0;
                    $scope.delivetype = 0; //默认付款、发票信息、邮寄信息不显示
                    $scope.getInvoiceList(); //添加新发票后，按照搜索条件刷新
                    return false;
                }
            });
        }

        /*添加专票信息功能*/
        $scope.imagesPost = function(_d) {
            var fd = new FormData();
            for (var i = $scope.imgAdd.length - 1; i >= 0; i--) {
                fd.append('img' + i, $scope.imgAdd[i]);
            };
            $http({
                method: 'POST',
                url: '/Admin/invoice/addImgs',
                data: fd,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            }).success(function(datas) {
                if (datas.rcode == 0) {
                    $(".ui.modal.postFail").modal('show');
                    setTimeout(function() {
                        $('.ui.modal.postFail').modal('hide')
                    }, 3000);
                } else {
                    var item = { d: _d, array: datas.data }
                    $scope.$emit("BUSY");
                    dataFactoryCRM.postDataByAPI('Invoice/addSpecial', item).then(function(d) {
                        if (d.rcode) {
                            $(".ui.small.modal.addOk").modal('show');
                            setTimeout(function() {
                                $('.ui.small.modal.addOk').modal('hide')
                            }, 3000);
                            $scope.invoicetype = 0;
                            $scope.customerVerify = 0;
                            $scope.delivetype = 0; //默认付款、发票信息、邮寄信息不显示
                            $scope.getInvoiceList(); //添加新发票后，按照搜索条件刷新
                        } else {
                            $(".ui.modal.addFail").modal('show');
                            setTimeout(function() {
                                $('.ui.modal.addFail').modal('hide')
                            }, 3000);
                            $scope.invoicetype = 0;
                            $scope.customerVerify = 0;
                            $scope.delivetype = 0; //默认付款、发票信息、邮寄信息不显示
                            $scope.getInvoiceList(); //添加新发票后，按照搜索条件刷新
                            return false;
                        }
                    });
                }
                $scope.addPic = new Array();
            })
        }

        /*编辑发票界面*/
        $scope.showEdit = function() {
            $("#frm-edit").form("");
            var _vinvoice = this.vinvoice;
            $scope.delivery_id = _vinvoice.delivery_id;
            $scope.edit_data = _vinvoice;
            $scope.getCusInfo('',_vinvoice.customer_id, '', _vinvoice.invoice_id);
            $scope.edit_data_invoicetype = _vinvoice.type;
            $scope.deliveryInfo = _vinvoice.deliveryInfo;
            var create_timeEdit = _vinvoice.deliveryInfo.create_time;
            $scope.send_timeEdit = create_timeEdit.substring(0, 10);
            if (_vinvoice.type == '1') { //普通发票
                $scope.edit_title = _vinvoice.title;
                $scope.payee_Edit = _vinvoice.payee;
                $scope.edit_remark = _vinvoice.remark;
                $scope.edit_money = _vinvoice.money;
                $scope.edit_data.tax = parseInt(_vinvoice.tax);
                $('#payeeID').dropdown('set selected', _vinvoice.payee);
                if ($scope.deliveryInfo) {
                    $scope.deliveryInfo.nickname = $scope.deliveryInfo.recipients;
                }
            } else if (_vinvoice.type == '2') { //专票
                $("#editPic_alt").val(_vinvoice.pic_alt);
                $scope.imgPostEdit_title = _vinvoice.title;
                $scope.imgPostEdit_money = _vinvoice.money;
                $scope.imgPostEdit_taxs = parseInt(_vinvoice.tax);
                $scope.Picinvoiceid = _vinvoice.invoice_id;
                if ($scope.deliveryInfo) {
                    $scope.deliveryInfo.nickname = $scope.deliveryInfo.recipients;
                }
                //根据发票id获取图片信息
                dataFactoryCRM.getDataByAPI('invoice/getInvImag?invoice_id=' + _vinvoice.invoice_id)
                    .then(function(d) {
                        $scope.imgEdit = d.data;
                        if (d.data) $scope.editPic_alt = d.data[0]['pic_alt'];
                    });
            }
            $('.ui.modal.edit').modal({
                observeChanges: true,
                onApprove: function() {
                    //重新获取已选择流水
                    $scope.pay_idEdit = $("input:checkbox[name='chbidsEdit']:checked").map(function(index, elem) {
                        return $(elem).val();
                    }).get().join(',');
                    if ($scope.pay_idEdit) {
                        if (_vinvoice.type == 1) { //普通发票
                            if (_vinvoice.delivery_id) { //发票邮寄
                                if ($('#frm-edit').form('is valid') && $('#delivery-edit').form('is valid')) {
                                    var _url = $('#frm-edit').serialize() + '&delivery_id=' + _vinvoice.delivery_id + '&pay_id=' + $scope.pay_idEdit + '&' + $('#delivery-edit').serialize() + '&invoice_id=' + _vinvoice.invoice_id + '&customer_id=';
                                    _url = _url + _vinvoice.customer_id + '&tax=' + $scope.edit_data.tax;
                                    $scope.editInvoice(_url); //编辑发票
                                } else return false;
                            } else if (!_vinvoice.delivery_id) { //发票自取
                                if ($('#frm-edit').form('is valid')) {
                                    var _url = $('#frm-edit').serialize() + '&invoice_id=' + _vinvoice.invoice_id + '&customer_id=';
                                    _url = _url + _vinvoice.customer_id + '&pay_id=' + $scope.pay_idEdit + '&tax=' + $scope.edit_data.tax;
                                    $scope.editInvoice(_url); //编辑发票
                                } else return false;
                            }
                        } else if (_vinvoice.type == 2) { //专票
                            if (_vinvoice.delivery_id) { //发票邮寄
                                if ($('#frm-editPost').form('is valid') && $('#delivery-edit').form('is valid')) {
                                    var editUrl = $('#frm-editPost').serialize() + '&delivery_id=' + _vinvoice.delivery_id + '&pay_id=' + $scope.pay_idEdit + '&' + $('#delivery-edit').serialize() + '&customer_id=' + _vinvoice.customer_id + '&invoice_id=' + _vinvoice.invoice_id;
                                    $scope.imagesEdit(editUrl);
                                } else return false;
                            } else if (!_vinvoice.delivery_id) {
                                if ($('#frm-editPost').form('is valid')) { //发票自取
                                    var editUrl = $('#frm-editPost').serialize() + '&pay_id=' + $scope.pay_idEdit + '&customer_id=' + _vinvoice.customer_id + '&invoice_id=' + _vinvoice.invoice_id;
                                    $scope.imagesEdit(editUrl);
                                } else return false;
                            } else {
                                return false;
                            }
                        }
                    } else { //未选择流水
                        $('#selectPaysEdit').addClass('ui basic red pointing prompt label transition visible');
                        document.getElementById("selectPaysEdit").innerHTML = '请选择付款流水！';
                        return false;
                    }
                }
            }).modal('show');
        }

        /*编辑普通发票功能*/
        $scope.editInvoice = function(urls) {
            $scope.$emit("BUSY");
            dataFactoryCRM.postDataByAPI('invoice/edit', urls)
                .then(function(d) {
                    if (d.rcode) {
                        $(".ui.small.modal.editOk").modal('show');
                        setTimeout(function() {
                            $('.ui.small.modal.editOk').modal('hide')
                        }, 3000);
                        $scope.customerVerify = 0;
                        $scope.getInvoiceList(); //编辑发票后，按照搜索条件刷新
                    } else {
                        $(".ui.modal.editFail").modal('show');
                        setTimeout(function() {
                            $('.ui.modal.editFail').modal('hide')
                        }, 3000);
                        $scope.customerVerify = 0;
                        $scope.getInvoiceList(); //编辑发票后，按照搜索条件刷新
                        return false;
                    }
                });
        }

        /*编辑专票信息功能*/
        $scope.imagesEdit = function(_d) {
            var oldPic = new Array();
            var addPic = new Array();
            var oldNum = 0;
            for (var i = 0; i < $scope.imgEdit.length; i++) {
                if ($scope.imgEdit[i].invoice_pic_id) {
                    oldPic[oldNum] = $scope.imgEdit[i];
                } else {
                    addPic[oldNum] = $scope.imgEdit[i];
                }
                oldNum++;
            }
            var fd = new FormData();
            for (var j = $scope.imgEdit.length - 1; j >= 0; j--) {
                fd.append('img' + j, $scope.imgEdit[j]);
            };
            $http({
                method: 'POST',
                url: "/Admin/invoice/editImg",
                data: fd,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            }).success(function(datas) {
                if (addPic.length != 0 && datas.rcode == 0) {
                    //编辑图片,图片上传失败
                    $(".ui.modal.postFail").modal('show');
                    setTimeout(function() {
                        $('.ui.modal.postFail').modal('hide')
                    }, 3000);
                    return false;
                } else if (addPic.length != 0 && datas.rcode == 1) {
                    //编辑图片,并且图片上传成功
                    var newPic = new Array();
                    newPic = $scope.transform(datas.data);
                    var totalPic = oldPic.concat(newPic);
                    var item = { d: _d, array: totalPic }
                    $scope.editSpec(item);
                } else if (addPic.length == 0) {
                    //未编辑图片
                    var item = { d: _d, array: oldPic }
                    $scope.editSpec(item);
                }
            })
        }

        /*编辑专票信息:图片信息+发票基本信息*/
        $scope.editSpec = function(item) {
            $scope.$emit("BUSY");
            dataFactoryCRM.postDataByAPI('Invoice/editSpecial', item).then(function(d) {
                if (d.rcode) {
                    $(".ui.modal.editOk").modal('show');
                    setTimeout(function() {
                        $('.ui.small.modal.editOk').modal('hide')
                    }, 3000);
                    $scope.customerVerify = 0;
                    $scope.getInvoiceList(); //编辑发票后，按照搜索条件刷新
                } else {
                    $(".ui.modal.editFail").modal('show');
                    setTimeout(function() {
                        $('.ui.modal.editFail').modal('hide')
                    }, 3000);
                    return false;
                }
            });
        }

        /*删除图片列表中已添加图片--添加页面*/
        $scope.delImg = function() {
                var index = this.$index;
                $scope.imgAdd.splice(index, 1);
            }
            /*删除图片列表中已添加图片--编辑页面*/
        $scope.delImg_edit = function() {
                var index = this.$index;
                $scope.imgEdit.splice(index, 1);
            }
            /*判断图片格式是否正确*/
        $scope.IsPic = function(file) {
                var mime = /\.[^\.]+/.exec(file['name']);
                var imgExt = ['.gif', '.GIF', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', 'BMP', '.png', '.PNG', '.swf', '.SWF'];
                if (imgExt.indexOf(mime[0]) > -1)
                    return true;
                else
                    return false;
            }
            /*添加新的图片--添加页面*/
        $scope.addChange = function(addPic) {
            if (addPic) {
                if ($scope.IsPic(addPic)) { //图片格式判断
                    if ($scope.imgAdd.length == 6) { //图片数量判断
                        $scope.invoiceRcode = 0;
                        $scope.invoiceMsg = '最多可上传6张图片，请重新添加！';
                        // 内弹窗  
                        $scope.msgAttention();
                    } else {
                        addPic.path = window.URL.createObjectURL(addPic);
                        if ($scope.imgAdd == null) {
                            var add = new Array();
                            add[0] = addPic;
                            $scope.imgAdd = add;
                        } else
                            $scope.imgAdd.push(addPic);
                    }
                } else {
                    $scope.invoiceRcode = 0;
                    $scope.invoiceMsg = '图片格式错误，请重新添加！';
                    $scope.msgAttention();
                }
            }
        };
        /*添加新的图片--编辑页面*/
        $scope.editChange = function(editPic) {
            if (editPic) {
                if ($scope.IsPic(editPic)) { //图片格式判断
                    if ($scope.imgEdit && $scope.imgEdit.length == 6) { //图片数量判断
                        $scope.invoiceRcode = 0;
                        $scope.invoiceMsg = '最多可上传6张图片，请重新添加！';
                        $scope.msgAttention();
                        return false;
                    } else {
                        editPic.pic_path = window.URL.createObjectURL(editPic);
                        if ($scope.imgEdit == null) {
                            var edit = new Array();
                            edit[0] = editPic;
                            $scope.imgEdit = edit;
                        } else
                            $scope.imgEdit.push(editPic);
                    }
                } else {
                    $scope.invoiceRcode = 0;
                    $scope.invoiceMsg = '图片格式错误，请重新添加！';
                    $scope.msgAttention();
                }
            }
        };

        /*对象转换为数组*/
        $scope.transform = function(obj) {
            var arr = [];
            for (var item in obj) {
                arr.push(obj[item]);
            }
            return arr;
        }

        /*导出发票*/
        $scope.invoiceExport = function() {
            var _url = 'invoice/invoiceExport?customer_name=' + $scope.customer_name + '&create_time=';
            _url = _url + $scope.create_time + '&end_time=' + $scope.end_time + '&pay_name=' + $scope.pay_name + '&status=' + $scope.key;
            dataFactoryCRM.getDataByAPIS(_url).then(function(data) {
                var blob = new Blob([data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, '发票数据记录表' + '.xls');
            });
        }

        /*查看发票信息*/
        $scope.showInvoice = function() {
            var _vinvoice = this.vinvoice;
            $scope.delivery_id = _vinvoice.delivery_id;
            $scope.invoicetype = _vinvoice.type;
            $scope.getCusInfo('',_vinvoice.customer_id, '', _vinvoice.invoice_id);
            $scope.edit_data = _vinvoice;
            $("#show_customer_name").text(_vinvoice.invpay_name);
            $('.ui.showeInvoice.modal').modal({ observeChanges: true, }).modal('show');
            //普通发票
            if (_vinvoice.type == 1) {
                $("#show_title").text(_vinvoice.title);
                var payeeName = "";
                switch (_vinvoice.payee) {
                    case '1':
                        payeeName = '北京和众汇富咨询有限公司北京分公司';
                        break;
                    case '2':
                        payeeName = '北京和众汇富咨询有限公司山东分公司';
                        break;
                    case '3':
                        payeeName = '北京和众汇富咨询有限公司天津分公司';
                        break;
                }
                $("#show_payee").text(payeeName);
                $("#show_money").text(_vinvoice.money);
                $("#show_tax").text(parseInt(_vinvoice.tax));
                $("#show_invoi_status").text(_vinvoice.status_name);
                $("#show_invoi_remark").text(_vinvoice.inv_remark);
            } else if (_vinvoice.type == 2) {
                //专票信息
                $("#special_title").text(_vinvoice.title);
                $("#special_money").text(_vinvoice.money);
                $("#special_tax").text(parseInt(_vinvoice.tax));
                $("#special_invoi_status").text(_vinvoice.status_name);
                //根据发票id获取图片信息
                dataFactoryCRM.getDataByAPI('invoice/getInvImag?invoice_id=' + _vinvoice.invoice_id)
                    .then(function(d) {
                        $scope.imgArr = d.data;
                        if ($scope.imgArr) $("#special_pic_alt").text($scope.imgArr[0]['pic_alt']);
                    });
            }
            if (_vinvoice.deliveryInfo) {
                $("#show_recipients").text(_vinvoice.deliveryInfo.recipients);
                $("#show_phone").text(_vinvoice.deliveryInfo.phone);
                $("#show_address").text(_vinvoice.deliveryInfo.address);
                $("#show_order_num").text(_vinvoice.deliveryInfo.order_num);
                $("#show_delivery_num").text(_vinvoice.deliveryInfo.delivery_num);
                $("#show_send_way").text(_vinvoice.deliveryInfo.send_way);
                $("#show_send_time").text(_vinvoice.deliveryInfo.send_time);
                var statusName = "";
                switch (_vinvoice.deliveryInfo.status) {
                    case '10': //待邮寄
                        statusName = '待邮寄';
                        break;
                    case '20': //确认邮寄
                        statusName = '确认邮寄';
                        break;
                    case '30': //邮寄中
                        statusName = '邮寄中';
                        break;
                    case '40': //邮寄完成
                        statusName = '邮寄完成';
                        break;
                }
                $("#show_status").text(statusName);
                $("#show_remark").text(_vinvoice.deliveryInfo.remark);
            }
        }

        /*自动加载页面*/
        $scope.adutoLoading = function() {
            $scope.getInvoiceList(4);
            $scope.getToday();
        };

        $scope.adutoLoading();

    });
});